<template>
  <div class="step-container">
    <a-card class="checkout-card">
      <div class="section">
        <h3>Order Products</h3>
        <p v-if="!selectedItems || selectedItems.length === 0" class="empty-tip">Your bag is empty</p>
        <div v-else>
          <div class="items-count">Your bag contains {{ selectedItems.length }} items</div>

          <!-- 使用a-table显示商品 -->
          <a-table
              :dataSource="selectedItems"
              :columns="columns"
              :pagination="false"
              size="small"
              class="product-table"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'image'">
                <img :src="record.image" :alt="record.name" class="product-image"/>
              </template>

              <template v-if="column.key === 'specs'">
                <div class="spec-cell">
                  <template v-if="parseSpecText(record.specs).imageUrl">
                    <div class="color-image-container">
                      <img :src="parseSpecText(record.specs).imageUrl" :alt="record.name" class="color-image"/>
                    </div>
                  </template>
                  <span class="spec-text">{{ parseSpecText(record.specs).size }}</span>
                </div>
              </template>

              <template v-if="column.key === 'subtotal'">
                <span class="subtotal">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice((record.price || 0) * (record.quantity || 1), false, false) }}</span>
              </template>
            </template>
          </a-table>
        </div>
      </div>

      <div class="section">
        <div class="order-summary">
          <div class="summary-row total">
            <span>Total:</span>
            <span>{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(totalPrice) }}</span>
          </div>
        </div>
      </div>
    </a-card>

    <div class="step-footer">
      <a-button @click="goBack">Return to the cart</a-button>
      <a-button type="primary" @click="nextStep">Next step</a-button>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, watch, ref, defineComponent, getCurrentInstance} from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useCurrencyStore } from '@/store';
const { proxy } = getCurrentInstance();
// 为组件定义名称
defineComponent({
  name: 'CheckoutStep1'
});

const router = useRouter();
const route = useRoute();
const useCurrency = useCurrencyStore();
const props = defineProps({
  selectedItems: {
    type: Array,
    default: () => []
  },
  currentStep: {
    type: Number,
    default: 0
  }
});

// 表格列定义
const columns = [
  {
    title: 'image',
    key: 'image',
    width: 80
  },
  {
    title: 'Product Name',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: 'Specification',
    key: 'specs'
  },
  {
    title: 'price',
    dataIndex: 'price',
    key: 'price',
    customRender: ({text}) => `${useCurrency.currentCurrency.unit}${(proxy.$ConvertPrice(text) || 0)}`
  },
  {
    title: 'quantity',
    dataIndex: 'quantity',
    key: 'quantity'
  },
  {
    title: 'subtotal',
    key: 'subtotal'
  }
];

const emit = defineEmits(['update:step', 'update:items']);

// 监听选中的商品变化
watch(() => props.selectedItems, (newItems) => {
  // 更新监听
}, {immediate: true});

// 总价计算
const totalPrice = computed(() => {
  try {
    if (!props.selectedItems || props.selectedItems.length === 0) {
      return '0.00';
    }

    const total = props.selectedItems
        .filter(item => item && typeof item.price === 'number' && typeof item.quantity === 'number')
        .reduce((sum, item) => {
          const price = Number(item.price) || 0;
          const quantity = Number(item.quantity) || 1;
          return sum + (price * quantity);
        }, 0);

    return total.toFixed(2);
  } catch (error) {
    console.error('An error occurred in calculating the total price:', error);
    return '0.00';
  }
});

const goBack = () => {
  router.push('/user/cart');
};

const nextStep = () => {
  emit('update:step', 1);
  emit('update:items', props.selectedItems);
};

// 解析规格文本
const parseSpecText = (specText) => {
  if (!specText) return {size: 'Default specifications', imageUrl: ''};

  // 检查是否包含图片URL和尺寸
  if (specText.includes('http') && specText.includes('，')) {
    const parts = specText.split('，');
    return {
      imageUrl: parts[0].trim(),
      size: parts[1].trim() || 'Default specifications'
    };
  }

  // 检查是否只有图片URL
  if (specText.includes('http')) {
    return {
      imageUrl: specText.trim(),
      size: 'Default specifications'
    };
  }

  // 只有尺寸
  return {
    imageUrl: '',
    size: specText.trim() || 'Default specifications'
  };
};

// 挂载时可以添加必要的初始化逻辑
onMounted(() => {
  // 初始化
});
</script>

<style scoped>
.step-container {
  max-width: 800px;
  margin: 0 auto;
}

.checkout-card {
  margin-bottom: 24px;
}

.section {
  padding: 16px;
}

.section h3 {
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
}

.empty-tip {
  color: #999;
  text-align: center;
  padding: 20px 0;
}

.items-count {
  margin-bottom: 16px;
  font-weight: bold;
}

.product-table {
  margin-top: 16px;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.spec-cell {
  display: flex;
  align-items: center;
}

.color-image-container {
  display: inline-block;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 8px;
  border: 1px solid #eee;
  vertical-align: middle;
  flex-shrink: 0;
}

.color-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.spec-text {
  color: #666;
  font-size: 13px;
  line-height: 1.2;
  word-break: break-word;
}

.subtotal {
  color: #ff4d4f;
  font-weight: bold;
}

.order-summary {
  background-color: #f9f9f9;
  padding: 16px;
  border-radius: 4px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.summary-row.total {
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px dashed #ddd;
}

.step-footer {
  display: flex;
  justify-content: space-between;
  padding: 16px 0;
}

@media (max-width: 768px) {
  .step-container {
    padding: 0 16px;
  }

  .step-footer {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
